home *** CD-ROM | disk | FTP | other *** search
- #include <string.h>
- #include <stdlib.h>
- #include "extras.h"
-
- int strrpl(string, ptrn, rpl, n)
- char *string, *ptrn, *rpl;
- int n;
- {
- register char *s, *t = string;
- char *u;
- register int count = 0;
- register char ptrn_1;
- int ptrn_len = strlen(ptrn), rpl_len = strlen(rpl);
- int store_len;
-
- if (!string || *string == '\0' || !ptrn || *ptrn == '\0' || n == 0)
- return 0;
-
- /* At worst, the string's size could increase by a factor of
- rpl_len/ptrn_len */
- if (rpl_len > ptrn_len)
- store_len = (strlen(string)/ptrn_len + 1) * rpl_len + 1;
- else
- store_len = strlen(string) + 1;
-
- s = u = (char *)malloc((size_t)store_len);
- ptrn_1 = *ptrn;
- for (;;) {
- if (*t == '\0') {
- *s = '\0';
- break;
- } else if (*t == ptrn_1 && strncmp(t, ptrn, ptrn_len) == 0 &&
- (n < 0 || count < n)) {
- strcpy(s, rpl);
- s += rpl_len;
- t += ptrn_len;
- count++;
- } else *s++ = *t++;
- }
- strcpy(string, u);
- free(u);
- return count;
- }
-